package com.origin.multimedia.music

import android.content.Context
import android.media.AudioManager
import tv.danmaku.ijk.media.player.IjkMediaPlayer

class IjkAudioPlayer constructor() {

    //    companion object {
//        val instance: IjkAudioPlayer by lazy(mode = LazyThreadSafetyMode.SYNCHRONIZED) {
//            IjkAudioPlayer()
//        }
//    }
    private var ijkMediaPlayer: IjkMediaPlayer? = null
//    private val ijkMediaPlayer: IjkMediaPlayer by lazy {
//        val imp = IjkMediaPlayer()
//        //设置是否开启变调
//        imp.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "soundtouch", 0);
//        // 设置播放前的最大探测时间
//        imp.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "analyzemaxduration", 50L);
//        imp.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "enable-accurate-seek", 1);
//        imp.setAudioStreamType(AudioManager.STREAM_MUSIC)
//        imp
//    }

    private fun initIjkMediaPlayer() {
        ijkMediaPlayer = IjkMediaPlayer()
        ijkMediaPlayer?.apply {
            //设置是否开启变调
            setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "soundtouch", 0);
            // 设置播放前的最大探测时间
            setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "analyzemaxduration", 50L);
            setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "enable-accurate-seek", 1);
            setAudioStreamType(AudioManager.STREAM_MUSIC)
        }


    }

    public fun getPlayer(): IjkMediaPlayer {

        if (ijkMediaPlayer == null) {
            initIjkMediaPlayer()
        }


        return ijkMediaPlayer!!
    }

    fun setPathAndPrepare(uri: String) {
        ijkMediaPlayer?.apply {
            dataSource = uri
            prepareAsync()
        }
    }

    fun start() {
        ijkMediaPlayer?.start();
    }

    fun pause() {
        ijkMediaPlayer?.pause()
    }


    fun stop() {
        ijkMediaPlayer?.stop()
    }

    fun seekTo(time: Long) {
        ijkMediaPlayer?.seekTo(time)
    }


    /**
     * 耗时
     */
    public fun reset() {
        ijkMediaPlayer?.reset()
    }

    public fun release() {
        ijkMediaPlayer?.apply {
            reset();
            release();
        }
        ijkMediaPlayer=null
    }


}